package com.auxgroup.smarthome;


import com.auxgroup.smarthome.utils.ProtocolConvertUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;

/**
 * Created by kevinchen on 2017/9/5.
 *  把数据点的值 转成 字节数组的工具
 *  支持家用空调、与商用空调的 采集查询控制参数指令
 *  协议详见A4表
 *  其中 家用空调的空调地址值固定为1
 *  商用的空调地址值为其关联的子设备的设备编号1-255
 */
public class QueryConvertUtils {

    public static final String CMD = "0600";

    public static final int CMD1= 0x06;

    public static final int CMD2 = 0x00;


    private static final String BC = "0200";

    private static final int BC1 = 0x02;

    private static final int BC2 = 0x00;

    private static final int DATA_LENGTH = BC1;


    private static final String SRC = "01";

    private static final int SRC1 = 0x01;

    private static final String[] COMMON_ARR = new String[]{CommonControlFunction.HEAD,CMD,
                                                CommonControlFunction.RET_CMD,BC};

    private static final int [] COMMON_INT_ARR = new int[]{CommonControlFunction.APP2_DEV_NUM,CommonControlFunction.HEAD1,
                                CommonControlFunction.HEAD2,CMD1,CMD2,
                                CommonControlFunction.RET_CMD1,CommonControlFunction.RET_CMD2,BC1,BC2};

    /**
     * 采集查询控制参数指令的原始raw
     * @param dstNum  空调地址值：家用固定为1 商用为其子设备的地址编号1-255
     * @return
     */
    private static Pair<String[],int[]> queryConvertData(int dstNum){
        if (dstNum < 1 || dstNum > 255){
            throw new IllegalArgumentException("传入的空调地址值参数不合法！");
        }
        String[] hexStrArr = new String[DATA_LENGTH];
        int[] hexNumArr = new int[DATA_LENGTH];
        hexStrArr[0] = SRC;
        hexNumArr[0] = SRC1;
        hexStrArr[1] = ProtocolConvertUtils.converDecimalto2HexStr(dstNum);
        hexNumArr[1] = dstNum;
        return Pair.of(hexStrArr,hexNumArr);
    }


    /**
     * 获取FCC 16进制 字符串
     * FCC = HEAD + CMD + RETCMD + BC + DATA (16进制拼接而成的字符串)
     * @param dataStr
     * @return
     */
    private static String[] getCheckFccHexStrArr(String[] dataStr){
        if (dataStr==null || dataStr.length <= 0){
            throw new IllegalArgumentException();
        }
        String[] data4HexStrArr = ProtocolConvertUtils.constructData4HexStrArr(dataStr);
        return ArrayUtils.addAll(COMMON_ARR, data4HexStrArr);

    }

    /**
     * 采集查询控制参数指令
     * @param dstNum
     * @return
     */
    public static int[] getA4ControlRaw(int dstNum){
        Pair<String[], int[]> dataPointConvertBytes = queryConvertData(dstNum);
        String[] leftDataHexArr = dataPointConvertBytes.getLeft();
        String[] fccHexStrArr = getCheckFccHexStrArr(leftDataHexArr);
        String fcc = CommonControlFunction.getFCC(fccHexStrArr);
        int[] fccNumArr = ProtocolConvertUtils.getFccNumArr(fcc);
        int[] rightArr = dataPointConvertBytes.getRight();
        int[] addArr = ArrayUtils.addAll(COMMON_INT_ARR, rightArr);
        return ArrayUtils.addAll(addArr,fccNumArr);
    }




}
